<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User_model extends DQ_Model 
{
    public function __construct()
    {
        parent::__construct();
    }

    public function getUserInfoByIds($uids,$fields=array('username','uid','status'))
    {
        $this->db->where_in('uid', $uids);
        $this->db->select(implode(',',$fields));
        $query = $this->db->get('uc_member');
        
        $res = array();
        foreach($query->result_array() as $value)
        {
            if($value['status'] == -1)
            {
                $res[$value['uid']] = array();
            }
            else
            {
                $res[$value['uid']] = $value;
            }
        }

        return $res;
    }

    public function suggest()
    {
        $checkedData = $this->checkInput(__FUNCTION__,0);
        $checkedData['uid'] = (int) $this->session->userdata('uid');

        $this->db->insert('suggest',array(
            'uid' => $checkedData['uid'],
            'email'=> $checkedData['email'],
            'dateline'=> date('Y-m-d H:i:s'),
            'message' => $checkedData['message']
        ));

        if($this->db->insert_id())
        {
            return array('error'=>0,'msg'=>$this->error_code[0],'data'=>1);
        }
        else
        {
            return array('error'=>7001,'msg'=>$this->error_code[7001],'data'=>0);
        }
    }

    public function setMemberDetail()
    {
        $checkedData = $this->checkInput(__FUNCTION__,0);
        $checkedData['authorid'] = $this->checkUser();

        $this->db->set('birthday', $checkedData['birthday']);
        $this->db->set('height', $checkedData['height']);
        $this->db->set('area', $checkedData['area']);
        $this->db->set('player_type', $checkedData['player_type']);
        $this->db->where('uid',$checkedData['authorid']);
        $this->db->update('uc_member_detail');
        $update_num = $this->db->affected_rows();

        $this->db->where('uid',$checkedData['authorid']);
        $this->db->update('uc_member',array('gender'=>$checkedData['gender']));

        return array('error'=>0,'msg'=>$this->error_code[0],'data'=>$update_num);
    }

    public function getUserInfoSummary()
    {
        $checkedData = $this->checkInput(__FUNCTION__);

        $this->db->select('uid,username,gender,avatar,score');
        $this->db->from('uc_member');
        $this->db->where('uc_member.uid',$checkedData['uid']);
        $query = $this->db->get();

        $userInfo = $query->row_array();

        if(empty($userInfo))
        {
            return array('error'=>4001,'msg'=>$this->error_code[4001],'data'=>array());
        }
        elseif($userInfo['status'] == -1)
        {
            return array('error'=>4002,'msg'=>$this->error_code[4002],'data'=>array());
        }
        else
        {
            return array('error'=>0,'msg'=>$this->error_code[0],'data'=>$userInfo);
        }
    }

    public function getUserInfoDetail($data = array())
    {
        if($data)
        {
            $checkedData = $data;
        }
        else
        {
            $checkedData = $this->checkInput('getUserInfoSummary');
        }

        $this->db->select('uc_member.email, uc_member.username, uc_member.gender, uc_member.avatar, uc_member.score, uc_member.status,uc_member_detail.*');
        $this->db->from('uc_member');
        $this->db->join('uc_member_detail', 'uc_member.uid = uc_member_detail.uid','left');
        $this->db->where('uc_member.uid',$checkedData['uid']);
        $query = $this->db->get();

        $userInfo = $query->row_array();

        if(empty($userInfo))
        {
            return array('error'=>4001,'msg'=>$this->error_code[4001],'data'=>array());
        }
        elseif($userInfo['status'] == -1)
        {
            return array('error'=>4002,'msg'=>$this->error_code[4002],'data'=>array());
        }
        else
        {
            return array('error'=>0,'msg'=>$this->error_code[0],'data'=>$userInfo);
        }
    }

    public function changePassword()
    {
        $checkedData = $this->checkInput(__FUNCTION__,0);
        $checkedData['authorid'] = $this->checkUser();

        $this->db->select('uid,password,salt,status');
        $this->db->from('uc_member');
        $this->db->where('uid',$checkedData['authorid']);
        $query = $this->db->get();

        $userInfo = $query->row_array();

        if(empty($userInfo))
        {
            return array('error'=>4001,'msg'=>$this->error_code[4001],'data'=>array());
        }
        elseif($userInfo['status'] == -1)
        {
            return array('error'=>4002,'msg'=>$this->error_code[4002],'data'=>array());
        }
        else
        {
            if(strtoupper(md5(strtoupper(md5($checkedData['oldPassword'].$userInfo['salt'])))) != $userInfo['password'])
            {
                return array('error'=>4005,'msg'=>$this->error_code[4005],'data'=>array());
            }
            elseif($checkedData['newPassword'] != $checkedData['rePassword'])
            {
                return array('error'=>6003,'msg'=>$this->error_code[6003],'data'=>0);
            }
            elseif($checkedData['oldPassword'] == $checkedData['newPassword'])
            {
                return array('error'=>4006,'msg'=>$this->error_code[4006],'data'=>0);
            }
            else
            {
                $update_num = $this->_changePassword($checkedData['authorid'],$checkedData['newPassword']);

                return array('error'=>0,'msg'=>$this->error_code[0],'data'=>$update_num);
            }
        }
    }

    private function _changePassword($uid,$password)
    {
        $salt     = random_string ('alpha', 8);
        $password = strtoupper(md5(strtoupper(md5 ($password. $salt)))); 
        $this->db->where('uid',$uid);
        $this->db->update('uc_member',array('salt'=>$salt,'password'=>$password));

        return $this->db->affected_rows();
    }

    //开始重置密码的流程
    public function addReset()
    {
        $captcha_error = $this->_checkCaptcha();

        if($captcha_error)
        {
            return $captcha_error;
        }

        $checkedData = $this->checkInput(__FUNCTION__,0);

        //检查是否有对应帐号
        $userData = $this->getUserInfoByAccount($checkedData['email']);

        if(empty($userData))
        {
            return array('error'=>7101,'msg'=>$this->error_code[7101],'data'=>0);
        }

        //检查是否可以发送
        $today_send = $this->getTodaySend($userData['uid']);

        if($today_send > TODAY_SEND)
        {
            return array('error'=>7102,'msg'=>$this->error_code[7102],'data'=>0);
        }

        $code = $this->getKeyCode(EMAIL_TYPE);

        //添加发送数据
        if(!$this->addVerifyData($userData['uid'],EMAIL_TYPE,$code))
        {
            return array('error'=>7103,'msg'=>$this->error_code[7103],'data'=>0);
        }

        $check_url = $this->generateForgetUrl($userData['uid'],$code);

        //发送邮件
        if(!$this->sendEmail($checkedData['email'],EMAIL_SUBJECT_FORGET,sprintf(EMAIL_MESSAGE_FORGET,$check_url,$check_url)))
        {
            return array('error'=>7104,'msg'=>$this->error_code[7104],'data'=>0);
        }
        else
        {
            return array('error'=>0,'msg'=>$this->error_code[0],'data'=>0);
        }
    }

    public function getUserInfoByAccount($account)
    {
        $this->db->where('email',$account);
        $this->db->where('status',0);
        $this->db->from('uc_member');
        $query = $this->db->get();
        return $query->row_array();
    }

    public function getTodaySend($uid)
    {
        $this->db->where('date(request_time)',date('Y-m-d'));
        $this->db->where('uid',$uid);
        $this->db->from('uc_identify_code');
        return $this->db->count_all_results();
    }

    private function addVerifyData($uid,$method_type,$code)
    {
        //将原先的置为失效
        $this->db->where('uid',$uid);
        $this->db->update('uc_identify_code',array('status'=>0));

        $this->db->insert('uc_identify_code',array(
            'uid'=>$uid,
            'method_type'=>$method_type,
            'code'=>$code,
            'request_time'=>date('Y-m-d H:i:s'),
            'status'=>1
        ));

        return $this->db->affected_rows();
    }

    private function generateForgetUrl($uid,$code)
    {
        return site_url("forget/reset/?uid=" . $uid.  "&verify=" . $code);
    }

    private function getKeyCode($type)
    {
        if($type == EMAIL_TYPE)
        {
            return getUUID();
        }
        else
        {
            return  random_string ('numeric',6);
        }
    }


    public function sendEmail($to,$subject,$message)
    {
        $this->config->load('email');
        $this->load->library('email');

        $this->email->from($this->config->item('smtp_from'), EMAIL_NAME);
        $this->email->to($to); 

        $this->email->subject($subject);
        $this->email->message($message);

        return $this->email->send();
    }

    //检查是否有权限重置密码
    public function checkReset()
    {
        $checkedData = $this->checkInput(__FUNCTION__);

        $this->db->where('uid',$checkedData['uid']);
        $this->db->where('code',$checkedData['verify']);
        $this->db->where('status',1);
        $this->db->order_by('request_time', 'desc'); 
        $query = $this->db->get('uc_identify_code');
        $data  = $query->row_array();

        if(empty($data) || strtotime($data['request_time']) + 86400 < time() )
        {
            return array('error'=>7105,'msg'=>$this->error_code[7105],'data'=>0);
        }
        else
        {
            $this->db->where('uid',$checkedData['uid']);
            $this->db->where('status',1);
            $this->db->update('uc_identify_code',array('status'=>0));
            
            $this->session->set_userdata('forget', array('uid'=>$checkedData['uid'],'time'=>time() + 300));
            
            return array('error'=>0,'msg'=>$this->error_code[0],'data'=>$checkedData['uid']);
        }
    }

    public function resetPassword()
    {
        $checkedData = $this->checkInput(__FUNCTION__,0);

        $forget = $this->session->userdata('forget');

        if(!empty($forget) && isset($forget['time']) && isset($forget['uid']) && $forget['time'] > time())
        {
            $uid = $forget['uid'];
        }
        else
        {
            return array('error'=>7105,'msg'=>$this->error_code[7105],'data'=>0);
        }

        $this->db->select('uid,password,salt,status,username');
        $this->db->from('uc_member');
        $this->db->where('uid',$uid);
        $query = $this->db->get();

        $userInfo = $query->row_array();

        if(empty($userInfo))
        {
            return array('error'=>4001,'msg'=>$this->error_code[4001],'data'=>array());
        }
        elseif($userInfo['status'] == -1)
        {
            return array('error'=>4002,'msg'=>$this->error_code[4002],'data'=>array());
        }
        else
        {
            if($checkedData['password'] != $checkedData['repassword'])
            {
                return array('error'=>6003,'msg'=>$this->error_code[6003],'data'=>0);
            }
            else
            {
                $this->load->model('login_model');
                $this->login_model->setLoginInfo($uid,$userInfo['username']);

                $this->session->unset_userdata('forget');
                $update_num = $this->_changePassword($uid,$checkedData['password']);

                return array('error'=>0,'msg'=>$this->error_code[0],'data'=>$update_num);
            }
        }
    }

}
